<template>
	<div class="page-info">
		<div class="search">
			<div class="search-box">
				<a-form
					:model="searchInfo"
					:label-col="labelCol"
					:wrapper-col="wrapperCol"
				>
					<a-row :gutter="24">
						<a-col :span="6">
							<a-form-item
								:name="labelMap['userCode'].name"
								:label="labelMap['userCode'].label"
							>
								<a-input
									v-model:value="searchInfo.userCode"
									placeholder="请输入用户编码"
									allow-clear
								/>
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item
								:name="labelMap['phone'].name"
								:label="labelMap['phone'].label"
							>
								<a-input
									v-model:value="searchInfo.phone"
									placeholder="请输入手机号"
									allow-clear
								/>
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item
								:name="labelMap['gender'].name"
								:label="labelMap['gender'].label"
							>
								<a-select
									v-model:value="searchInfo.gender"
									placeholder="请选择性别"
									allowClear
								>
									<a-select-option value="0">男</a-select-option>
									<a-select-option value="1">女</a-select-option>
								</a-select>
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item
								:name="labelMap['region'].name"
								:label="labelMap['region'].label"
							>
								<a-cascader
									v-model:value="searchInfo.region"
									:options="locationTree"
									:placeholder="'请填写' + labelMap['region'].label"
									:load-data="loadData"
									:fieldNames="{
										label: 'name',
										value: 'id',
										children: 'children',
									}"
									change-on-select
									@change="handleRegionChange"
									allow-clear
								/>
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item
								:name="labelMap['ageRange'].name"
								:label="labelMap['ageRange'].label"
							>
								<a-input-group compact>
									<a-input-number
										v-model:value="searchInfo.ageMin"
										placeholder="最小年龄"
										style="width: 50%"
										:min="1"
										:max="searchInfo.ageMax || 500"
										allow-clear
									/>
									<a-input-number
										v-model:value="searchInfo.ageMax"
										placeholder="最大年龄"
										style="width: 50%"
										:min="searchInfo.ageMin || 1"
										:max="500"
										allow-clear
									/>
								</a-input-group>
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item
								:name="labelMap['heightRange'].name"
								:label="labelMap['heightRange'].label"
							>
								<a-input-group compact>
									<a-input-number
										v-model:value="searchInfo.heightMin"
										placeholder="最小身高(cm)"
										style="width: 50%"
										:min="1"
										:max="searchInfo.heightMax || 500"
										allow-clear
									/>
									<a-input-number
										v-model:value="searchInfo.heightMax"
										placeholder="最大身高(cm)"
										style="width: 50%"
										:min="searchInfo.heightMin || 100"
										:max="500"
										allow-clear
									/>
								</a-input-group>
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item
								:name="labelMap['weightRange'].name"
								:label="labelMap['weightRange'].label"
							>
								<a-input-group compact>
									<a-input-number
										v-model:value="searchInfo.weightMin"
										placeholder="最小体重(kg)"
										style="width: 50%"
										:min="1"
										:max="searchInfo.weightMax || 500"
										allow-clear
									/>
									<a-input-number
										v-model:value="searchInfo.weightMax"
										placeholder="最大体重(kg)"
										style="width: 50%"
										:min="searchInfo.weightMin || 1"
										:max="500"
										allow-clear
									/>
								</a-input-group>
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item
								:name="labelMap['profession'].name"
								:label="labelMap['profession'].label"
							>
								<a-select
									style="width: 90%; margin-left: 8px"
									ref="select"
									v-model:value="searchInfo.profession"
									:placeholder="'请选择' + labelMap['profession'].label"
									:field-names="{ label: 'typeName', value: 'typeCode' }"
									:options="professionTypeList"
									:allowClear="true"
								>
								</a-select>
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item
								:name="labelMap['incomeStatus'].name"
								:label="labelMap['incomeStatus'].label"
							>
								<a-select
									style="width: 90%; margin-left: 8px"
									ref="select"
									v-model:value="searchInfo.incomeStatus"
									:placeholder="'请选择' + labelMap['incomeStatus'].label"
									:field-names="{ label: 'typeName', value: 'typeCode' }"
									:options="incomeStatusTypeList"
									:allowClear="true"
								>
								</a-select>
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item
								:name="labelMap['maritalStatus'].name"
								:label="labelMap['maritalStatus'].label"
							>
								<a-select
									style="width: 90%; margin-left: 8px"
									ref="select"
									v-model:value="searchInfo.maritalStatus"
									:placeholder="'请选择' + labelMap['maritalStatus'].label"
									:field-names="{ label: 'typeName', value: 'typeCode' }"
									:options="maritalStatusTypeList"
									:allowClear="true"
								>
								</a-select>
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item
								:name="labelMap['carHouseStatus'].name"
								:label="labelMap['carHouseStatus'].label"
							>
								<a-select
									style="width: 90%; margin-left: 8px"
									ref="select"
									v-model:value="searchInfo.carHouseStatus"
									:placeholder="'请选择' + labelMap['carHouseStatus'].label"
									:field-names="{ label: 'typeName', value: 'typeCode' }"
									:options="carHouseStatusTypeList"
									:allowClear="true"
								>
								</a-select>
							</a-form-item>
						</a-col>
						<a-col style="text-align: right; margin-bottom: 20px">
							<a-space>
								<a-button type="primary" @click="query"> 查找</a-button>
								<a-button type="primary" @click="cancelQuery">清空</a-button>
							</a-space>
						</a-col>
					</a-row>
				</a-form>
			</div>
		</div>
		<div class="button" style="margin: 10px">
			<a-space>
				<a-button type="primary" @click="editUserMembershipInfo('add')"
					>新增</a-button
				>
				<a-button type="primary" @click="exportUserMembershipInfo"
					>导出</a-button
				>
			</a-space>
		</div>
		<div class="content">
			<a-table
				:dataSource="dataSource"
				:columns="columns"
				:loading="loading"
				:row-key="(record) => record.id"
				:pagination="pagination"
				@change="handleTableChange"
				:scroll="{ x: 1600, y: 470 }"
				:row-selection="rowSelection"
			>
				<template #bodyCell="{ column, record }">
					<template v-if="column.key === 'code'">
						{{ record?.userInfoVo?.code }}
					</template>
					<template v-if="column.key === 'phone'">
						{{ record?.userInfoVo?.phone }}
					</template>
					<template v-if="column.key === 'nickname'">
						{{ record?.userProfileInfoVo?.nickname }}
					</template>
					<template v-else-if="column.key === 'realName'">
						{{ record?.identityVerificationVo?.name || '-' }}
					</template>
					<template v-else-if="column.key === 'idCard'">
						{{
							record?.identityVerificationVo?.idCardNumber ?
								record.identityVerificationVo.idCardNumber.length > 10 ?
									record.identityVerificationVo.idCardNumber.substring(0, 6) +
									'****' +
									record.identityVerificationVo.idCardNumber.substring(
										record.identityVerificationVo.idCardNumber.length - 4,
									)
								:	record.identityVerificationVo.idCardNumber
							:	'-'
						}}
					</template>
					<template v-else-if="column.key === 'gender'">
						{{
							record?.userProfileInfoVo?.gender === '0' ? '男'
							: record?.userProfileInfoVo?.gender === '1' ? '女'
							: '-'
						}}
					</template>
					<template v-else-if="column.key === 'region'">
						{{
							[
								record?.userProfileInfoVo?.provinceName,
								record?.userProfileInfoVo?.cityName,
								record?.userProfileInfoVo?.districtName,
							]
								.filter(Boolean)
								.join('/') || '-'
						}}
					</template>
					<template v-else-if="column.key === 'age'">
						{{ calculateAge(record?.userProfileInfoVo?.birthYearMonth) }}
					</template>
					<template v-else-if="column.key === 'height'">
						{{ record?.userProfileInfoVo?.height || '-' }}
					</template>
					<template v-else-if="column.key === 'weight'">
						{{ record?.userProfileInfoVo?.weight || '-' }}
					</template>
					<template v-else-if="column.key === 'income'">
						{{ record?.userProfileInfoVo?.incomeStatusName || '-' }}
					</template>
					<template v-else-if="column.key === 'profession'">
						{{ record?.userProfileInfoVo?.professionName || '-' }}
					</template>
					<template v-else-if="column.key === 'maritalStatus'">
						{{ record?.userProfileInfoVo?.maritalStatusName || '-' }}
					</template>
					<template v-else-if="column.key === 'carHouseStatus'">
						{{ record?.userProfileInfoVo?.carHouseStatusName || '-' }}
					</template>
					<template v-if="column.key === 'operation'">
						<!--   <a-button
                type="primary"
                size="small"
                @click="editUserMembershipInfo('update', record.id)"
                >编辑</a-button
              > -->
						<a-popconfirm
							title="确认删除?"
							ok-text="确认"
							cancel-text="取消"
							@confirm="delUserMembershipInfo(record.id)"
							@cancel="cancel"
						>
							<a-button type="primary" size="small" danger>删除</a-button>
						</a-popconfirm>
					</template>
					<template v-else-if="column.key === 'memberFlag'">
						<a-tag
							:key="record.memberFlag"
							:color="record.memberFlag ? '#87d068' : 'grey'"
						>
							{{ record.memberFlag ? '激活' : '已过期' }}
						</a-tag>
					</template>
					<template v-else-if="column.key === 'startTime'">
						{{
							record.startTime ?
								dayjs(record.startTime).format('YYYY-MM-DD')
							:	''
						}}
					</template>
					<template v-else-if="column.key === 'endTime'">
						{{
							record.endTime ? dayjs(record.endTime).format('YYYY-MM-DD') : ''
						}}
					</template>
					<template v-else-if="column.key === 'operateTime'">
						{{
							record.operateTime ?
								dayjs(record.operateTime).format('YYYY-MM-DD')
							:	''
						}}
					</template>
				</template>
			</a-table>
			<UserMembershipInfoDetail
				ref="editInfo"
				:open="visible"
				:modelInfo="modelInfo"
				@handleOk="handleOk"
				@handleCancel="handleCancel"
			></UserMembershipInfoDetail>
		</div>
	</div>
</template>
<script setup lang="ts">
import { columns, DataItem, ModelInfo, pageInfo, pagination, SearchInfo } from './userMembershipInfoListTs';
import {
	deleteUserMembershipInfo,
	exportUserMembership,
	getUserMembershipInfoPage,
} from '@/api/membershipInfo/userMembershipInfo/userMembershipInfoTs';
import { message } from 'ant-design-vue';
import dayjs from 'dayjs';
import { getLocationTree } from '@/api/eventInfo/eventInfo/eventInfoTs';
import { getDictList } from '@/api/commonInfo/dictInfo/dictInfoTs';

const labelCol = ref({ span: 5 });
const wrapperCol = ref({ span: 19 });

const locationTree = ref<any[]>([]);

const incomeStatusTypeList = ref<any[]>([]);
const professionTypeList = ref<any[]>([]);
const maritalStatusTypeList = ref<any[]>([]);
const carHouseStatusTypeList = ref<any[]>([]);

let visible = ref<boolean>(false);

let modelInfo = ref<ModelInfo>({});

let rowIds;

const rowSelection = ref({
	checkStrictly: false,
	onChange: (
		selectedRowKeys: (string | number)[],
		selectedRows: DataItem[],
	) => {
		rowIds = selectedRowKeys;
	},
	onSelect: (record: DataItem, selected: boolean, selectedRows: DataItem[]) => {
		console.log(record, selected, selectedRows);
	},
	onSelectAll: (
		selected: boolean,
		selectedRows: DataItem[],
		changeRows: DataItem[],
	) => {
		console.log(selected, selectedRows, changeRows);
	},
});

const labelMap = ref<any>({
	userId: { name: 'userId', label: '用户ID' },
	membershipId: { name: 'membershipId', label: '会员ID，关联会员配置' },
	startTime: { name: 'startTime', label: '会员时间从' },
	endTime: { name: 'endTime', label: '会员时间到' },
	memberNumber: { name: 'memberNumber', label: '会员号' },
	userCode: { name: 'userCode', label: '用户编码' },
	phone: { name: 'phone', label: '手机号' },
	gender: { name: 'gender', label: '性别' },
	region: { name: 'region', label: '地域' },
	ageRange: { name: 'ageRange', label: '年龄段' },
	heightRange: { name: 'heightRange', label: '身高范围' },
	weightRange: { name: 'weightRange', label: '体重范围' },
	profession: { name: 'profession', label: '职业' },
	incomeStatus: { name: 'incomeStatus', label: '年收入' },
	maritalStatus: { name: 'maritalStatus', label: '婚姻状况' },
	carHouseStatus: { name: 'carHouseStatus', label: '车房情况' },
});

let searchInfo = ref<SearchInfo>({});

// 根据生日计算年龄
const calculateAge = (birthday: string | null | undefined): string => {
	if (!birthday) return '-';

	try {
		const birthDate = dayjs(birthday);
		const currentDate = dayjs();

		if (!birthDate.isValid()) return '-';

		const age = currentDate.diff(birthDate, 'year');
		return age >= 0 ? `${age}岁` : '-';
	} catch (error) {
		return '-';
	}
};

const loadData = async (selectedOptions: any[]) => {
	const targetOption = selectedOptions[selectedOptions.length - 1];

	// 如果选择的是"全部"选项，直接返回，不查询下一级
	if (targetOption.id === 'all') {
		targetOption.loading = false;
		return;
	}

	targetOption.loading = true;

	// 判断当前级别，最多3级
	const currentLevel = selectedOptions.length;
	if (currentLevel >= 3) {
		targetOption.loading = false;
		return;
	}

	targetOption.children = await getLocationTreeInfo(
		targetOption.id,
		currentLevel + 1,
	);
	if (targetOption.children.length == 0) {
		targetOption.loading = false;
		return;
	}

	targetOption.children.forEach((item: any) => {
		if (currentLevel == 1) {
			// 第二级，除了"全部"选项外，其他都可以继续展开
			item.isLeaf = item.id === 'all';
			item.level = 2;
		} else if (currentLevel == 2) {
			// 第三级，所有选项都是叶子节点
			item.isLeaf = true;
			item.level = 3;
		}
	});

	targetOption.loading = false;
};

const getLocationTreeInfo = async (
	parentId: number,
	level?: number,
): Promise<any> => {
	const {
		data,
		code,
		message: messageInfo,
	} = await getLocationTree({ parentId }).catch((error: any) => {
		message.error(error?.message || '查询失败！');
	});
	if (code == '200') {
		let result = data || [];

		// 如果不是根级别且有数据，添加"全部"选项
		if (parentId !== 0 && result.length > 0) {
			const allOption = {
				id: 'all',
				name: '全部',
				isLeaf: true,
				level: level || 1,
			};
			result = [allOption, ...result];
		}

		return result;
	} else {
		message.error(messageInfo || '查询失败！');
		return [];
	}
};

const handleRegionChange = (value: any, selectedOptions: any[]) => {
	// 如果选择了"全部"选项，处理特殊逻辑
	if (value && value.includes('all')) {
		// 如果最后一级选择的是"全部"，保持当前选择
		const lastSelectedOption = selectedOptions[selectedOptions.length - 1];
		if (lastSelectedOption && lastSelectedOption.id === 'all') {
			// 移除"全部"，保留前面的实际选择
			const newValue = value.slice(0, -1);
			searchInfo.value.region = newValue;
		}
	}
};

const cancelQuery = (): void => {
	searchInfo.value = {};
};

const query = (): void => {
	getUserMembershipInfoListPage(pagination.value);
};

const handleTableChange = (pagination: any): void => {
	getUserMembershipInfoListPage(pagination);
};

const delUserMembershipInfo = (ids: string): void => {
	deleteUserMembershipInfo(ids).then((res) => {
		if (res.code == '200') {
			message.success((res && '删除' + res.message) || '删除成功！', 3);
			getUserMembershipInfoListPage(pagination.value);
		} else {
			message.error((res && res.message) || '删除失败！', 3);
		}
	});
};

let loading = ref<boolean>(false);

let dataSource = ref();

const cancel = (e: MouseEvent): void => {
	console.log(e);
};

const getUserMembershipInfoListPage = (cur: pageInfo): void => {
	loading.value = true;
	getUserMembershipInfoPage(getQueryparams(), cur.current, cur.pageSize)
		.then((res: any) => {
			console.log(`getUserMembershipInfoListPage`, res);
			if (res.code == '200') {
				dataSource.value = res.data.records;
				pagination.value.current = res.data.current;
				pagination.value.pageSize = res.data.size;
				pagination.value.total = res.data.total;
			} else {
				message.error((res && res.message) || '查询列表失败！');
			}
		})
		.finally(() => {
			loading.value = false;
		});
};

const getDictInfoList = (): void => {
	getDictList('income,profession,matrimony,assets').then((res: any) => {
		if (res.code == '200') {
			incomeStatusTypeList.value = res.data.filter(
				(item: { belongTo: string }) => item.belongTo == 'income',
			);
			professionTypeList.value = res.data.filter(
				(item: { belongTo: string }) => item.belongTo == 'profession',
			);
			maritalStatusTypeList.value = res.data.filter(
				(item: { belongTo: string }) => item.belongTo == 'matrimony',
			);
			carHouseStatusTypeList.value = res.data.filter(
				(item: { belongTo: string }) => item.belongTo == 'assets',
			);
		} else {
			message.error((res && res.message) || '查询列表失败！');
		}
	});
};

const init = async (): Promise<void> => {
	getDictInfoList();
	// 初始化时获取第一级数据，level为1
	const firstLevelData = await getLocationTreeInfo(0, 1);
	// 为第一级数据设置属性
	locationTree.value = firstLevelData.map((item: any) => ({
		...item,
		isLeaf: item.id === 'all', // "全部"选项是叶子节点
		level: 1,
	}));
	//获取用户会员表页面数据
	getUserMembershipInfoListPage(pagination.value);
};

//新增和修改弹窗
const editUserMembershipInfo = (type: string, id?: number): void => {
	if (type == 'add') {
		modelInfo.value.title = '新增明细';
		modelInfo.value.id = undefined;
	} else if (type == 'update') {
		modelInfo.value.title = '修改明细';
		modelInfo.value.id = id;
	}
	modelInfo.value.confirmLoading = true;
	visible.value = true;
};

const handleOk = (v: boolean): void => {
	visible.value = v;
	getUserMembershipInfoListPage(pagination.value);
};

const handleCancel = (v: boolean): void => {
	visible.value = v;
};

const exportUserMembershipInfo = () => {
	exportUserMembership(getQueryparams(), { responseType: 'blob' }) // 设置 responseType 为 'blob'
		.then((response: any) => {
			const blob = new Blob([response.data], {
				type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
			});
			const url = window.URL.createObjectURL(blob);
			const link = document.createElement('a');
			link.href = url;
			link.setAttribute('download', '会员名单.xlsx'); // 设置文件名
			document.body.appendChild(link);
			link.click();
			document.body.removeChild(link);
			window.URL.revokeObjectURL(url); // 释放内存
		})
		.catch((error: any) => {
			console.error('Error exporting Excel:', error);
		});
};

const getQueryparams = (): any => {
	let params: any = {};

	// 基础属性转换
	if (searchInfo.value.userId !== undefined)
		params.userId = searchInfo.value.userId;
	if (searchInfo.value.membershipId !== undefined)
		params.membershipId = searchInfo.value.membershipId;
	if (
		searchInfo.value.memberNumber !== undefined &&
		searchInfo.value.memberNumber !== ''
	)
		params.memberNumber = searchInfo.value.memberNumber;
	if (
		searchInfo.value.userCode !== undefined &&
		searchInfo.value.userCode !== ''
	)
		params.userCode = searchInfo.value.userCode;
	if (searchInfo.value.phone !== undefined && searchInfo.value.phone !== '')
		params.phone = searchInfo.value.phone;
	if (searchInfo.value.gender !== undefined && searchInfo.value.gender !== '')
		params.gender = searchInfo.value.gender;

	// 时间属性转换
	if (searchInfo.value.startTime) {
		params.startTime =
			typeof searchInfo.value.startTime === 'string' ?
				searchInfo.value.startTime
			:	dayjs(searchInfo.value.startTime).format('YYYY-MM-DD');
	}
	if (searchInfo.value.endTime) {
		params.endTime =
			typeof searchInfo.value.endTime === 'string' ?
				searchInfo.value.endTime
			:	dayjs(searchInfo.value.endTime).format('YYYY-MM-DD');
	}

	// 年龄范围转换
	if (searchInfo.value.ageMin !== undefined)
		params.ageMin = searchInfo.value.ageMin;
	if (searchInfo.value.ageMax !== undefined)
		params.ageMax = searchInfo.value.ageMax;

	// 身高范围转换
	if (searchInfo.value.heightMin !== undefined)
		params.heightMin = searchInfo.value.heightMin;
	if (searchInfo.value.heightMax !== undefined)
		params.heightMax = searchInfo.value.heightMax;

	// 体重范围转换
	if (searchInfo.value.weightMin !== undefined)
		params.weightMin = searchInfo.value.weightMin;
	if (searchInfo.value.weightMax !== undefined)
		params.weightMax = searchInfo.value.weightMax;

	// 职业转换
	if (
		searchInfo.value.profession !== undefined &&
		searchInfo.value.profession !== ''
	)
		params.profession = searchInfo.value.profession;

	// 收入范围转换
	if (
		searchInfo.value.incomeStatus !== undefined &&
		searchInfo.value.incomeStatus !== ''
	)
		params.incomeStatus = searchInfo.value.incomeStatus;

	// 婚姻状况转换
	if (
		searchInfo.value.maritalStatus !== undefined &&
		searchInfo.value.maritalStatus !== ''
	)
		params.maritalStatus = searchInfo.value.maritalStatus;

	// 车房情况转换
	if (
		searchInfo.value.carHouseStatus !== undefined &&
		searchInfo.value.carHouseStatus !== ''
	)
		params.carHouseStatus = searchInfo.value.carHouseStatus;

	// region数组转换为省市区单独字段
	if (
		searchInfo.value.region &&
		Array.isArray(searchInfo.value.region) &&
		searchInfo.value.region.length > 0
	) {
		// 过滤掉'all'值，只保留实际的地区ID
		const validRegion = searchInfo.value.region.filter(
			(item: any) => item !== 'all',
		);

		if (validRegion.length >= 1) params.provinceId = validRegion[0];
		if (validRegion.length >= 2) params.cityId = validRegion[1];
		if (validRegion.length >= 3) params.districtId = validRegion[2];
	}
	return params;
};

init();

// 监听最小值变化，确保最大值不小于最小值
watch(
	() => searchInfo.value.ageMin,
	(newVal) => {
		if (newVal && searchInfo.value.ageMax && searchInfo.value.ageMax < newVal) {
			searchInfo.value.ageMax = undefined;
		}
	},
);

watch(
	() => searchInfo.value.heightMin,
	(newVal) => {
		if (
			newVal &&
			searchInfo.value.heightMax &&
			searchInfo.value.heightMax < newVal
		) {
			searchInfo.value.heightMax = undefined;
		}
	},
);

watch(
	() => searchInfo.value.weightMin,
	(newVal) => {
		if (
			newVal &&
			searchInfo.value.weightMax &&
			searchInfo.value.weightMax < newVal
		) {
			searchInfo.value.weightMax = undefined;
		}
	},
);
</script>
<style lang="scss" scoped></style>
